#!/usr/bin/env python
# coding=utf-8
#
#       gamepad.py
#       
#       Copyright 2008 Dirk B. <dirkbo@googlemail.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
import pygame
import os, sys
from pygame.locals import *

class Gamepad():
	def __init__(self,jid):	
		#Gibt an, ob Gamepad verwendbar ist
		self.configured = False
		
		if jid != -1:
			self.stick = pygame.joystick.Joystick(jid)
			self.stick.init()
		self.id = jid
		## Aktionsknopf
		self.actionbutton = 0
		## Lenkachse
		self.lenkachse = 0
		## Gas-Achse
		self.gasachse = 0
		
	def save(self):
		n = self.stick.get_name() + ".conf"
		name = n.replace(' ', '_')
		filename = os.path.join("data/gamepads/", name)
		fp = open(filename, "w")
		res = self.stick.get_name() + "\n" + str(self.actionbutton) + "\n" + str(self.gasachse) + "\n" + str(self.lenkachse) + "\n"
		fp.write(res)
		fp.close()
		#leere Datei System-Bezeichnung.conf anlegen
		#Knopfbelegung speichern
		
	def load(self):
		n = str(self.stick.get_name()) + ".conf"
		name = n.replace(' ', '_')
		try:
			##Datei öffnen
			fp = open(os.path.join("data/gamepads/", name))
			content = fp.read()
			##Inhalt Zeile für Zeile in Array laden
			line = []
			line.append("")
			lcount = 0
			for i in range(0, len(content)):
				if content[i] == '\n':
					line.append("")
					#print "Zeile komplett: ", line[lcount]
					lcount += 1	
				else:
					line[lcount] += content[i]
					
			if line[0] == self.stick.get_name():
				self.configure(int(line[1]), int(line[2]), int(line[3]))
			else:
				print("Name und Name in der Datei stimmen nicht überein!")
			#versuchen, datei System-Bezeichnung.conf anlegen
			#Knopfbelegung laden
		except:
			print "Datei " + name + "nicht gefunden!"
			
	def configure(self, action_bt, gas_ax, lenk_ax):
		self.actionbutton = action_bt
		self.gasachse = gas_ax
		self.lenkachse = lenk_ax
		self.configured = True
		
	
	